package com.kpl.kplstzble.fragment;

import static com.kpl.kplstzble.fragment.UpgradationFragment.write;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextSwitcher;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.kpl.kplstzble.R;
import com.kpl.kplstzble.activity.HomeActivity;
import com.kpl.kplstzble.utils.DataTrasportUtil;
import java.text.DecimalFormat;

public class HomeFragment extends Fragment {
    private TextView history_data;
    private View mapLayout;
    private View pupupViewrealtime;
    private View pupupViewsurround;
    private TextSwitcher textSwitcher;
    private TextView workmethod;
    private Button mac_width;

    //实时测量弹出框
    private SeekBar realtimeseekBar;
    private TextView realtimetvProgress;
    //绕圈测量弹出框
    private SeekBar surroundseekBar;
    private TextView surroundtvProgress;
    private SharedPreferences sharedPref;
    private SharedPreferences.Editor editor;
    private PopupWindow popupWindow;
    private int curmethod = 0;

    DecimalFormat df = new DecimalFormat("0.0");//设置保留位数
    String[] string = new String[]{
            "实时测量",
            "绕圈测量"
    };
    String[] width = new String[]{
            "车载宽幅",
            "车载边距"
    };
    String[] stringwidth = new String[]{
            "实时车载宽幅",
            "绕圈车载边距"
    };

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mapLayout = inflater.inflate(R.layout.page_home, null);
        //两个弹窗的视图
        pupupViewrealtime = getLayoutInflater().inflate(R.layout.realtime_macwidth, null);
        pupupViewsurround = getLayoutInflater().inflate(R.layout.surround_macwidth, null);
        //存储车载宽度数据
        sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        editor = sharedPref.edit();
        curmethod=sharedPref.getInt("curmethod", 0);
        //主页上的一些操作
        homeaction();
        //实时测量界面上的一些操作
        realtimeaction();
        //绕圈测量界面上的一些操作
        surroundaction();
        return mapLayout;
    }
    public  void homeaction(){
        //文字闪烁效果
        final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
        animation.setDuration(300); // duration - half a second
        animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
        animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
        animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in
        //主界面显示已连接蓝牙
        TextView bluetooth = mapLayout.findViewById(R.id.bluetooth);
        if(HomeActivity.bleDevice==null){
            bluetooth.startAnimation(animation);
        }else {
            bluetooth.setText(HomeActivity.bleDevice.getName()+"已连接");
            bluetooth.clearAnimation();
            bluetooth.setText(HomeActivity.bleDevice.getName()+"已连接");
        }
        //历史数据入口
        history_data = mapLayout.findViewById(R.id.history_data);
        history_data.setOnClickListener(view->{
                history_data.clearAnimation();
                HistoryDataFragment historyDataFragment = (HistoryDataFragment) HistoryDataFragment.newInstance();
                FragmentManager fm = getActivity().getSupportFragmentManager();
                fm.beginTransaction().replace(R.id.fl_content,historyDataFragment)
                        .addToBackStack(null).commit();
                        //.setCustomAnimations(R.anim.fragment_enter, R.anim.fragment_exit).commit();
            }
        );

        //工作模式文字滚动
        textSwitcher = mapLayout.findViewById(R.id.textSwitcher);
        textSwitcher.setFactory(()->{
                TextView textView = new TextView(getActivity());
                textView.setTextSize(18);
                textView.setText(string[curmethod]);
                //textView.setTextColor(Color.BLACK);
                return textView;

        });
        textSwitcher.setOnClickListener(view->{

        });
        //切换工作模式
        workmethod = mapLayout.findViewById(R.id.workmethod);
        workmethod.setText(string[1 -curmethod]);
        workmethod.setOnClickListener(view->{
                curmethod = 1 - curmethod;
                editor.putInt("curmethod",curmethod);
                editor.commit();
                workmethod.setText(string[1 - curmethod]);
                textSwitcher.setText(string[curmethod]);
                mac_width.setText("   "+width[curmethod] + df.format((float) sharedPref.getInt(stringwidth[curmethod], 30) / 10) + "m   ");

        });

        //这一步是为了获取屏幕的宽高，便于用来设置PopupWindow的大小
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //车载宽幅文字
        mac_width = mapLayout.findViewById(R.id.mac_width);
        mac_width.setText("   "+width[curmethod]+ df.format((float) sharedPref.getInt(stringwidth[curmethod], 30) / 10) + "m   ");
        mac_width.setOnClickListener(view->{
                if(curmethod==0){//实时测量
                    popupWindow = new PopupWindow(pupupViewrealtime, dm.widthPixels/11*8,dm.heightPixels/11*5, true);
                }else if(curmethod==1){
                    popupWindow = new PopupWindow(pupupViewsurround, dm.widthPixels/11*8,dm.heightPixels/11*5, true);
                }
                popupWindow.setTouchable(true);
                popupWindow.setOutsideTouchable(false);
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                popupWindow.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER,0,0);
        });
        //开始测量按钮跳转至地图界面
        Button start_measure = mapLayout.findViewById(R.id.start_measure);
        start_measure.setOnClickListener(view -> {
            if(HomeActivity.bleDevice!=null){
                HomeActivity.read("开始测量");
                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                MeasureFragment measureFragment=new MeasureFragment(HomeActivity.bleDevice.getName(),curmethod,sharedPref.getInt("实时车载宽幅", 30),sharedPref.getInt("绕圈车载边距", 30));
                ft.hide(this).add(R.id.fl_content, measureFragment).show(measureFragment).commit();
            }else {
                HomeActivity.read("设备尚未连接,请连接后重试");
            }
        });
        ImageView upgradation = mapLayout.findViewById(R.id.upgradation);
        upgradation.setOnClickListener(view -> {
            //if(HomeActivity.bleDevice!=null){
                UpgradationFragment upgradationFragment = new UpgradationFragment();
                getFragmentManager().beginTransaction().replace(R.id.fl_content,upgradationFragment).addToBackStack(null).commit();
           /* }else {
                HomeActivity.read("设备尚未连接,请连接后重试");
            }*/
        });
        ImageView forcesetcode = mapLayout.findViewById(R.id.forcesetcode);
        forcesetcode.setOnClickListener(view -> {
            String data ="XJXY140240100003";
            String hexdata = DataTrasportUtil.stringToHex(data);
            hexdata=hexdata+"0000";

            byte check = DataTrasportUtil.calculateChecksum(DataTrasportUtil.HexString2Bytes(hexdata));
            String checkdata = DataTrasportUtil.byteToHex(check);
            String senddata = "82" + checkdata + hexdata;
            System.out.println("发送："+senddata);
            write(senddata);
        });
    }
    public void realtimeaction(){
        ///注册拖动监听器
        realtimeseekBar= pupupViewrealtime.findViewById(R.id.realtimeseekBar);
        realtimetvProgress=pupupViewrealtime.findViewById(R.id.realtimetvProgress);
        realtimetvProgress.setText( df.format((float) sharedPref.getInt("实时车载宽幅", 30) / 10));
        realtimeseekBar.setProgress(sharedPref.getInt("实时车载宽幅", 30));
        Button realtimeleftbtn = pupupViewrealtime.findViewById(R.id.realtimeleftbtn);
        Button realtimerightbtn = pupupViewrealtime.findViewById(R.id.realtimerightbtn);
        Button realtimesure = pupupViewrealtime.findViewById(R.id.realtimesure);
        realtimeseekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //将seekBar的进度设置在textView上
                realtimetvProgress.setText(df.format((float) progress/ 10));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        realtimeleftbtn.setOnClickListener(view -> {
            if(Double.parseDouble(realtimetvProgress.getText().toString())>1){
                String format = df.format((float) (Double.parseDouble(realtimetvProgress.getText().toString()) * 10 - 1) / 10);
                realtimeseekBar.setProgress((int) (Double.parseDouble(realtimetvProgress.getText().toString()) * 10 - 1));
                realtimetvProgress.setText(format);
            }
        });
        realtimerightbtn.setOnClickListener(view -> {
            String format = df.format((float) (Double.parseDouble(realtimetvProgress.getText().toString()) * 10 + 1) / 10);
            realtimeseekBar.setProgress((int) (Double.parseDouble(realtimetvProgress.getText().toString()) * 10 + 1));
            realtimetvProgress.setText(format);
        });
        realtimesure.setOnClickListener(view -> {
            editor.putInt("实时车载宽幅", (int)(Double.parseDouble(realtimetvProgress.getText().toString()) * 10));
            editor.commit();
            mac_width.setText("车载宽幅" + df.format((float) sharedPref.getInt("实时车载宽幅", 30) / 10) + "m");
            popupWindow.dismiss();
        });
    }
    public void surroundaction(){
        ///注册拖动监听器
        surroundseekBar= pupupViewsurround.findViewById(R.id.surroundseekBar);
        surroundseekBar.setProgress(sharedPref.getInt("绕圈车载边距", 30));
        surroundtvProgress=pupupViewsurround.findViewById(R.id.surroundtvProgress);
        surroundtvProgress.setText(df.format((float) sharedPref.getInt("绕圈车载边距", 30) / 10));
        Button surroundleftbtn = pupupViewsurround.findViewById(R.id.surroundleftbtn);
        Button surroundrightbtn = pupupViewsurround.findViewById(R.id.surroundrightbtn);
        Button surroundsure = pupupViewsurround.findViewById(R.id.surroundsure);
        surroundseekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //将seekBar的进度设置在textView上
                surroundtvProgress.setText(df.format((float) progress/ 10));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        surroundleftbtn.setOnClickListener(view -> {
            if(Double.parseDouble(surroundtvProgress.getText().toString())>0){
                String format = df.format((float) (Double.parseDouble(surroundtvProgress.getText().toString()) * 10 - 1) / 10);
                surroundseekBar.setProgress((int) (Double.parseDouble(surroundtvProgress.getText().toString()) * 10 - 1));
                surroundtvProgress.setText(format);
            }
        });
        surroundrightbtn.setOnClickListener(view -> {
            String format = df.format((float) (Double.parseDouble(surroundtvProgress.getText().toString()) * 10 + 1) / 10);
            surroundseekBar.setProgress((int) (Double.parseDouble(surroundtvProgress.getText().toString()) * 10 + 1));
            surroundtvProgress.setText(format);
        });
        surroundsure.setOnClickListener(view -> {
            editor.putInt("绕圈车载边距", (int)(Double.parseDouble(surroundtvProgress.getText().toString()) * 10));
            editor.commit();
            mac_width.setText("车载边距" + df.format((float) sharedPref.getInt("绕圈车载边距", 30) / 10) + "m");
            popupWindow.dismiss();
        });
    }

}
